import Vue from 'vue'

const creatDataDictService = () => import('~/service/service-common/dict.service')
const createLoginService = () => import('~/service/service-manage/login.service')

export default async function ({ store, router }) {
  let { DictService } = await creatDataDictService()
  let { LoginService } = await createLoginService()

  let dataDictService = new DictService()
  let loginService = new LoginService()

  // 启动数据初始化
  let flag = await Promise.all([
    updateDataDict(),
    updateUserData()
  ]).then(() => {
    return true
  }).catch(ex => {
    // 基础数据初始化失败
    return false
  })

  // // 初始化业务数据
  // if (flag) {
  //   await updateBusinessData()
  // }

  store.commit('ready', true)

  /**
   * 检测用户数据
   */
  async function updateUserData() {
    return new Promise((reslove, reject) => {
      // 登录页面不更新用户数据
      if (!store.state.userToken && window.location.pathname == "/") {
        reslove()
        return
      }

      // 不存在token不更新用户数据
      if (!store.state.userToken && window.location.pathname != "/") {
        store.commit("updateTokenExpire", true)
        reject()
        return
      }

      // 更新用户数据
      loginService.getUserInfoByToken().subscribe(({ userInfo }) => {
        // 更新用户控件资源
        store.dispatch('updateUserLoginData', { userInfo })
        reslove()
      }, () => {
        // 用户数据获取异常
        store.commit("updateTokenExpire", true)
        reject()
      })
    })
  }

  /**
   * 检查数据字典
   * @param reslove
   */
  function updateDataDict() {
    return new Promise((reslove, reject) => {
      if (!store.state.dataDict) {
        return getDataDict(reslove, reject)
      }

      dataDictService.getAllDict().subscribe(() => {
        if (store.state.dataDict! == store.state.dataDict) {
          getDataDict(reslove, reject)
        } else {
          reslove()
        }
      }, () => {
        reject()
      })
    })
  }

  /**
   * 获取数据字典
   * @param reslove
   */
  function getDataDict(reslove, reject) {
    return dataDictService.getAllDict().subscribe((data) => {
      store.commit('updateDataDict', data)
      reslove()
    }, () => {
      reject()
    })
  }
}
